<template>
    <div class="outbound-statistics-container">
        <!-- 统计卡片 -->
        <div class="statistics-cards">
            <el-card class="stat-card">
                <div class="stat-value">{{ statistics.totalOrders }}</div>
                <div class="stat-label">出库单数量</div>
            </el-card>
            <el-card class="stat-card">
                <div class="stat-value">{{ statistics.totalProducts }}</div>
                <div class="stat-label">出库货品数量</div>
            </el-card>
            <el-card class="stat-card">
                <div class="stat-value">{{ statistics.totalAmount }}</div>
                <div class="stat-label">出库货品金额</div>
            </el-card>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <el-button>导出</el-button>
            <el-button @click="handleRefresh">刷新</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%" v-loading="loading">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
            <el-table-column label="出库编号" width="150" align="center">
                <template #default="{ row }">
                    {{ row.outboundCode || row.OutboundCode || '' }}
                </template>
            </el-table-column>
            <el-table-column label="出库日期" width="150" align="center">
                <template #default="{ row }">
                    {{ formatDate(row.outboundDate || row.OutboundDate) }}
                </template>
            </el-table-column>
            <el-table-column label="关联单号" width="150" align="center">
                <template #default="{ row }">
                    {{ row.relationalID || row.RelationalID || '' }}
                </template>
            </el-table-column>
            <el-table-column label="客户名称" width="120" align="center">
                <template #default="{ row }">
                    {{ row.contact || row.Contact || '' }}
                </template>
            </el-table-column>
            <el-table-column label="收货人" width="120" align="center">
                <template #default="{ row }">
                    {{ row.consignee || row.Consignee || '' }}
                </template>
            </el-table-column>
            <el-table-column label="电话" width="120" align="center">
                <template #default="{ row }">
                    {{ row.contactPhone || row.ContactPhone || '' }}
                </template>
            </el-table-column>
            <el-table-column label="备注" width="150" align="center">
                <template #default="{ row }">
                    {{ row.remark || row.Remark || '' }}
                </template>
            </el-table-column>
            <el-table-column label="出库总数量" width="120" align="center">
                <template #default="{ row }">
                    {{ row.outboundAllNum || row.OutboundAllNum || '' }}
                </template>
            </el-table-column>
            <el-table-column label="出库总金额" width="120" align="center">
                <template #default="{ row }">
                    {{ row.outboundAllMoney || row.OutboundAllMoney || '' }}
                </template>
            </el-table-column>
            <el-table-column label="出库货品" width="150" align="center">
                <template #default="{ row }">
                    {{ row.outboundAllGoods || row.OutboundAllGoods || '' }}
                </template>
            </el-table-column>
            <el-table-column label="创建人" width="120" align="center">
                <template #default="{ row }">
                    {{ row.creator || row.Creator || '' }}
                </template>
            </el-table-column>
            <el-table-column label="创建时间" width="150" align="center">
                <template #default="{ row }">
                    {{ formatDate(row.createDate || row.CreateDate) }}
                </template>
            </el-table-column>
            <el-table-column label="是否删除" width="100" align="center">
                <template #default="{ row }">
                    {{ row.isDelete || row.IsDelete || '' }}
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 30, 50, 100]" :total="pagination.total" :background="true"
                layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();
const loading = ref(false);

// 统计数据
const statistics = reactive({
    totalOrders: 0,
    totalProducts: 0,
    totalAmount: 0
});

// 分页配置
const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
});

// 表格数据
const tableData = ref([]);

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 处理分页大小变化
const handleSizeChange = (val) => {
    console.log('📄 每页显示数量改变:', val);
    pagination.pageSize = val;
    pagination.currentPage = 1; // 改变每页大小时，重置到第一页
    loadData();
};

// 处理当前页变化
const handleCurrentChange = (val) => {
    console.log('📄 当前页码改变:', val);
    pagination.currentPage = val;
    loadData();
};

// 刷新数据
const handleRefresh = () => {
    loadData();
};

// 加载数据
const loadData = async () => {
    loading.value = true;
    try {
        const response = await proxy.http.get('/api/Outbound/GetOutbound', {
            params: {
                pageIndex: pagination.currentPage,
                pageSize: pagination.pageSize
            }
        });

        console.log('=== API返回完整数据 ===', response);
        console.log('response.code:', response?.code);
        console.log('response.data:', response?.data);
        console.log('response.data.data:', response?.data?.data);
        console.log('response.totalCount:', response?.totalCount);

        // 修改判断逻辑：适配不同的API响应格式
        if (response && response.data) {
            let dataList = [];
            let total = 0;

            // 情况1: response.data.data 是数组
            if (response.data.data && Array.isArray(response.data.data)) {
                dataList = response.data.data;
                total = response.data.totalCount || response.data.total || response.data.count || dataList.length;
                console.log('✅ 使用 response.data.data');
            }
            // 情况2: response.data 直接是数组
            else if (Array.isArray(response.data)) {
                dataList = response.data;
                total = response.totalCount || response.total || response.count || dataList.length;
                console.log('✅ 使用 response.data (数组)');
            }
            // 情况3: 检查 response 顶层是否有 totalCount
            if (response.totalCount) {
                total = response.totalCount;
                console.log('✅ 使用 response.totalCount:', total);
            }

            console.log('=== 解析后的数据列表 ===', dataList);
            console.log('当前页数据条数:', dataList.length);
            console.log('总记录数:', total);
            console.log('当前页码:', pagination.currentPage);
            console.log('每页大小:', pagination.pageSize);

            // 确保 tableData 是数组
            tableData.value = dataList;
            pagination.total = total;

            // 计算统计数据
            if (tableData.value && tableData.value.length > 0) {
                console.log('第一条数据示例:', tableData.value[0]);

                // 统计出库单数量（去重）
                const outboundCodes = tableData.value
                    .map(item => item.outboundCode || item.OutboundCode)
                    .filter(code => code);
                const uniqueOutboundCodes = new Set(outboundCodes);
                statistics.totalOrders = uniqueOutboundCodes.size;

                // 统计出库货品数量 - 使用 outboundAllNum
                statistics.totalProducts = tableData.value.reduce((sum, item) => {
                    const qty = parseFloat(item.outboundAllNum || item.OutboundAllNum) || 0;
                    return sum + qty;
                }, 0);

                // 统计出库货品金额 - 使用 outboundAllMoney
                statistics.totalAmount = tableData.value.reduce((sum, item) => {
                    const money = parseFloat(item.outboundAllMoney || item.OutboundAllMoney) || 0;
                    return sum + money;
                }, 0).toFixed(2);

                console.log('统计结果 - 单数量:', statistics.totalOrders, '货品数量:', statistics.totalProducts, '金额:', statistics.totalAmount);
            } else {
                // 如果没有数据，重置统计
                statistics.totalOrders = 0;
                statistics.totalProducts = 0;
                statistics.totalAmount = '0.00';
                console.log('没有数据，统计已重置');
            }
        } else {
            console.warn('API响应异常:', response);
            tableData.value = [];
            pagination.total = 0;
        }
    } catch (error) {
        console.error('=== 加载数据失败 ===', error);
        console.error('错误详情:', error.message);
        console.error('错误堆栈:', error.stack);
        tableData.value = [];
        if (proxy && proxy.$message) {
            proxy.$message.error('加载数据失败: ' + error.message);
        }
    } finally {
        loading.value = false;
    }
};

// 页面加载时获取数据
onMounted(() => {
    loadData();
});
</script>

<style lang="less" scoped>
.outbound-statistics-container {
    padding: 20px;

    .statistics-cards {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;

        .stat-card {
            flex: 1;
            text-align: center;

            .stat-value {
                font-size: 32px;
                font-weight: bold;
                color: #409EFF;
                margin-bottom: 10px;
            }

            .stat-label {
                font-size: 14px;
                color: #606266;
            }
        }
    }

    .action-buttons {
        margin-bottom: 20px;
        display: flex;
        gap: 10px;
    }

    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }
}
</style>
